import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

// import.meta.env.BASE_URL 指向配置文件vite.config.ts中配置的base

// 创建路由实例   new
const router = createRouter({
  // 路由模式  mode   hash/history
  history: createWebHistory(import.meta.env.BASE_URL), // 创建history模式路由
  // history: createWebHashHistory(), // 创建hash模式路由
  // 路由表 核心配置
  routes: [
    { path: '/login', component: () => import('@/views/Login/LoginIndex.vue') },
    {
      path: '/',
      component: () => import('@/views/Layout/LayoutIndex.vue'),
      redirect: '/home',
      children: [
        { path: '/home', component: () => import('@/views/Home/HomeIndex.vue') },
        { path: '/article', component: () => import('@/views/Article/ArticleIndex.vue') },
        { path: '/notify', component: () => import('@/views/Notify/NotifyIndex.vue') },
        { path: '/user', component: () => import('@/views/User/UserIndex.vue') }
      ]
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/Consult/ConsultFast.vue'),
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/Consult/ConsultDep.vue'),
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/Consult/ConsultIllness.vue'),
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue')
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/Consult/ConsultPay.vue'),
    },
    {
      path: '/room',
      component: () => import('@/views/Room/RoomIndex.vue'),
      // 聊天室的进入有条件  必须支付成功  我需要单独给这个路由配置拦截
      beforeEnter(to) {
        // http://localhost:5173/room?orderId=7201807023988736&payResult=true&type=2
        // to 要去的页面  to.path  to.query查询参数  to.params动态路由参数
        if (to.query.payResult === 'false') {
          // 支付失败  去一边去
          return '/user/consult'
        }
      }
    },


  ]

})

router.beforeEach((to) => {
  // next('/login')    return '/login'
  // next()            return true  不返回

  // 用户仓库
  const store = useUserStore()
  // 不需要登录的页面，白名单
  const wihteList = ['/login']
  // 如果没有登录且不在白名单内，去登录
  if (!store.user?.token && !wihteList.includes(to.path)) {
    // 没登陆 且 去的不是白名单页面
    // 拦截去登录
    return '/login'
  }

  // return true // 放行
})

export default router

// vue3 vue-router4  pinia
